package com.aplink.generic.util;

import java.io.File;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

public class CameraUtils {
    public static final boolean ENABLE_SAVE_IMG_ON_INTERNAL_MEMORY = false;

    public static File getFile(final Context context, final String filename) {
        if (CameraUtils.ENABLE_SAVE_IMG_ON_INTERNAL_MEMORY) {
            final String path = context.getFilesDir().getPath() + filename;
            final File file = new File(path);
            return file;
        } else {
            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {
                return new File(Environment.getExternalStorageDirectory(),
                        filename);
            } else {
                return null;
            }
        }
    }

    public static Intent getIntentCropImage(final Uri uri, final Context context) {
        final Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setData(uri);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        final Uri tmpPath = CameraUtils.getUriCaptureTemp(context);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tmpPath);
        return intent;
    }

    private static Uri getUriCaptureTemp(final Context context) {

        final String temporaryName = String.format(Locale.getDefault(),
                "%d.jpeg", System.currentTimeMillis());

        final File file = CameraUtils.getFile(context, temporaryName);
        if (file != null) {
            return Uri.fromFile(file);
        }

        return null;
    }

    /**
     * Utility for taking picture from Camera app.
     * 
     * @return a valid Intent that we can start Camera app for taking photo.
     */
    public static Intent startCameraToTakePhoto(final Context context) {
        if (context == null) {
            return null;
        }
        Intent takePhotoIntent = null;
        takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                CameraUtils.getUriCaptureTemp(context));
        return takePhotoIntent;
    }
}
